package com.wang.luntan.users.head.interceptor;

import com.wang.luntan.common.pojo.ApiResponse;
import com.wang.luntan.common.pojo.ApiResponseEnum;
import com.wang.luntan.common.util.ConstatFinalUtil;
import com.wang.luntan.common.web.controller.BaseController;
import com.wang.luntan.users.pojo.AtUsers;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import lombok.extern.log4j.Log4j2;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import java.util.Collections;

/**
 * 登陆验证的拦截器
 *
 * @author wangsh
 */
@Component("authInterceptor")
@Log4j2
public class AuthInterceptor extends BaseController implements HandlerInterceptor {
    /**
     * 先执行
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        log.info("--授权拦截器执行--");
        /* 加载一些公共的变量 */
        this.commonOper(request);
        ApiResponse<Object> apiResponse = new ApiResponse<Object>();
        HttpSession session = request.getSession();
        /* 获取用户对象 */
        AtUsers users = (AtUsers) this.findObjfromSession(request, "users");
        if (users == null) {
            apiResponse.setCode(ApiResponseEnum.INFO_LOGIN_ILLEGAL.getStatus());
            apiResponse.setInfo(ConstatFinalUtil.INFO_JSON.getString(apiResponse.getCode() + ""), Collections.EMPTY_MAP);
            /* 提示信息 */
            session.setAttribute("response", apiResponse.toJSON());

            response.sendRedirect(request.getContextPath() + "/login.htm");
            return false;
        }
        return true;
    }
}
